﻿Imports System.IO
Imports System.Data
Imports MetodosComuns
Imports extranet.BC
Imports extranet.BE

Imports System.Collections.Generic
Imports EnhancedFileUpload

Partial Class AdmPerfil
  Inherits System.Web.UI.Page

  Private Const MESSAGE_ERRO_NA_INSERCAO As String = "Erro na inserção do Registro!."
  Private Const MESSAGE_ERRO_NA_ALTERACAO As String = "Erro na atualização do Registro!."
  Private Const MESSAGE_ERRO_NA_EXCLUSAO As String = "Erro na exclusão do Registro!."

  Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
    Dim objBEUsuario As extranet.BE.BEUsuario = Session("objBEUsuario")
    'If objBEUsuario IsNot Nothing AndAlso objBEUsuario.GrupoAcesso.Nome.ToUpper() = "ADMIN" Then
    '    Me.MasterPageFile = HttpRuntime.AppDomainAppVirtualPath & "/AdmMaster.master"
    'Else
    '    Me.MasterPageFile = HttpRuntime.AppDomainAppVirtualPath & "/NavegacaoMaster.master"
    'End If
  End Sub

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    '==================       PROCEDIMENTO  PADRÃO  SEGURANÇA     =============================
    Dim objBESeguranca As BESeguranca
    Dim objBEUsuario As BEUsuario = Session("objBEUsuario")
    If IsNothing(objBEUsuario) Then Response.Redirect(TELA_LOGOUT)
    Session("strTela") = MetodosComuns.GetCurrentPageName()
    If Not IsPostBack Then          ' SEGURANÇA
      objBESeguranca = BCSeguranca.SelecionaPermissoes(objBEUsuario.GrupoAcesso, Session("strTela"))
      If Not objBESeguranca.Autorizado Then Response.Redirect(TELA_LOGOUT)
      Session("objBESeguranca") = objBESeguranca
    Else
      objBESeguranca = Session("objBESeguranca")
    End If

    '==================       ALTERAR SE FOR NECESSARIO          ===============================
    If Not IsPostBack Then
      mostraDados(ESTADO_DETALHE)
    End If
  End Sub

  Protected Sub mostraMensagemDeErro(ByVal message As String)
    lblErro.Visible = True
    lblErro.Text = message
  End Sub

  Protected Sub mostraDados(ByVal estado As Int16)
    Dim objBESeguranca As BESeguranca = DirectCast(Session("objBESeguranca"), BESeguranca)
    lblErro.Visible = False

    ' SEGURANÇA
    Select Case estado
      Case ESTADO_INICIAL, ESTADO_DETALHE
        If Not objBESeguranca.Leitura Then estado = ESTADO_BLOQUEADO
      Case ESTADO_EDICAO
        If Not objBESeguranca.Modificacao Then estado = IIf(objBESeguranca.Leitura, ESTADO_DETALHE, ESTADO_BLOQUEADO)
      Case ESTADO_CADASTRO
        If Not objBESeguranca.Escrita Then estado = IIf(objBESeguranca.Leitura, ESTADO_DETALHE, ESTADO_BLOQUEADO)
    End Select

    ' Set o estado do Form View
    Select Case estado
      Case ESTADO_INICIAL, ESTADO_BUSCA, ESTADO_LISTA
        fv_Usuario.ChangeMode(FormViewMode.ReadOnly)
      Case ESTADO_DETALHE
        fv_Usuario.ChangeMode(FormViewMode.ReadOnly)
      Case ESTADO_EDICAO
        fv_Usuario.ChangeMode(FormViewMode.Edit)
    End Select

    ' Set Registro(s) segundo o estado
    Select Case estado
      Case ESTADO_INICIAL, ESTADO_DETALHE, ESTADO_EDICAO
        mostraRegistro()
        If Not estado = ESTADO_EDICAO Then mostraRecados()
      Case ESTADO_CADASTRO
    End Select

  End Sub

  Protected Sub fv_Usuario_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles fv_Usuario.DataBound
    Dim objBESeguranca As BESeguranca = DirectCast(Session("objBESeguranca"), BESeguranca)
    Select Case fv_Usuario.CurrentMode
      Case FormViewMode.Insert
      Case FormViewMode.Edit
      Case FormViewMode.ReadOnly
        With objBESeguranca
          If Not .Modificacao Then fv_Usuario.FindControl("lnkEditar").Visible = False
        End With
    End Select
  End Sub

  Protected Sub lnkEditar_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    mostraDados(ESTADO_EDICAO)
  End Sub

  Protected Sub mostraRegistro()
    Dim listUsuario As List(Of BEUsuario) = BCUsuario.Selecionar(DirectCast(Session("objBEUsuario"), BEUsuario).Usuario)
    If listUsuario.Count() > 0 Then lblTituloPagina.Text = listUsuario(0).Nome
    fv_Usuario.DataSource = listUsuario
    fv_Usuario.DataBind()
    setTrigger()
  End Sub

  Protected Sub mostraRecados()
    Dim objGrid As GridView = fv_Usuario.FindControl("grvRecados")
    If objGrid IsNot Nothing Then
      Dim listRecados As List(Of extranet.BE.BERecado) = extranet.BC.BCRecado.Selecionar(DirectCast(Session("objBEUsuario"), extranet.BE.BEUsuario).Usuario)
      With objGrid
        .DataSource = listRecados
        .DataBind()
      End With
    End If
  End Sub

  Protected Sub setTrigger()
    Dim trigger As New PostBackTrigger()
    Dim scm As ScriptManager = scriptManager.GetCurrent(Me.Page)
    Dim ctrl As Control
    If Not fv_Usuario.CurrentMode = FormViewMode.ReadOnly Then
      ctrl = fv_Usuario.FindControl(IIf(fv_Usuario.CurrentMode = FormViewMode.Insert, "btnCadastrar", "btnAtualizar"))
      trigger.ControlID = ctrl.ClientID
      updPanel.Triggers.Add(trigger)
      scm.RegisterPostBackControl(ctrl)
    End If
  End Sub

  Protected Sub ddl_Franquia_Init(ByVal sender As Object, ByVal e As System.EventArgs)
    DirectCast(sender, DropDownList).DataSource = BCFranquia.Selecionar()
  End Sub

  Protected Sub btnCancelarAlteracao_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    mostraDados(ESTADO_DETALHE)
  End Sub

  Protected Sub fv_Usuario_ItemUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewUpdateEventArgs) Handles fv_Usuario.ItemUpdating
    Dim strNovaSenha1 As String = DirectCast(fv_Usuario.FindControl("txt_Senha1"), TextBox).Text
    Dim strNovaSenha2 As String = DirectCast(fv_Usuario.FindControl("txt_Senha2"), TextBox).Text
    If strNovaSenha1.Equals(strNovaSenha2) AndAlso processaRegistro() Then
      fv_Usuario_ItemUpdated(sender, Nothing)
    Else
      If strNovaSenha1.Length > 0 Then mostraMensagemDeErro("As senhas digitadas não são iguais")
      setTrigger()
    End If
  End Sub

  Protected Sub fv_Usuario_ItemUpdated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewUpdatedEventArgs) Handles fv_Usuario.ItemUpdated
    mostraDados(ESTADO_DETALHE)
  End Sub

  Protected Function processaRegistro() As Boolean
    Dim boolInsercao As Boolean = (fv_Usuario.CurrentMode = FormViewMode.Insert)
    Dim usuario As New BEUsuario()
    Dim booSucesso As Boolean = True
    Try
      Dim iuAvatar As ImageUpload = fv_Usuario.FindControl("iu_Avatar")
      Dim strAvatar As String = DirectCast(fv_Usuario.FindControl("lbl_Avatar"), Label).Text
      Dim booLimpaAvatar As Boolean = DirectCast(fv_Usuario.FindControl("cb_ExcluirAvatar"), CheckBox).Checked
      If iuAvatar.HasFile Then
        iuAvatar.saveImage()
        If Not iuAvatar.ImageName = strAvatar AndAlso strAvatar.Length > 0 Then File.Delete(HttpContext.Current.Server.MapPath("~/imagens/avatar/") & strAvatar)
        strAvatar = iuAvatar.ImageName
      ElseIf booLimpaAvatar AndAlso strAvatar.Length > 0 Then
        File.Delete(HttpContext.Current.Server.MapPath("~/imagens/avatar/") & strAvatar)
        strAvatar = ""
      End If

      With usuario
        .Usuario = DirectCast(fv_Usuario.FindControl("txt_Usuario"), TextBox).Text
        .Nome = DirectCast(fv_Usuario.FindControl("txt_Nome"), TextBox).Text
        .Avatar = strAvatar
        .Cpf = DirectCast(fv_Usuario.FindControl("txt_Cpf"), TextBox).Text
        .Franquia = New BEFranquia(Integer.Parse(DirectCast(fv_Usuario.FindControl("lbl_IdFranquia"), Label).Text), _
                               DirectCast(fv_Usuario.FindControl("txt_Franquia"), TextBox).Text)
        .GrupoAcesso = New BEGrupoAcesso(Integer.Parse(DirectCast(fv_Usuario.FindControl("lbl_IdGrupo"), Label).Text), _
                                         DirectCast(fv_Usuario.FindControl("txt_GrupoAcesso"), TextBox).Text, "")
        .Pais = DirectCast(fv_Usuario.FindControl("txt_Pais"), TextBox).Text
        .Uf = DirectCast(fv_Usuario.FindControl("ddl_Uf"), DropDownList).SelectedValue
        .Cidade = DirectCast(fv_Usuario.FindControl("txt_Cidade"), TextBox).Text
        .Cep = DirectCast(fv_Usuario.FindControl("txt_Cep"), TextBox).Text
        .Logradouro = DirectCast(fv_Usuario.FindControl("txt_Logradouro"), TextBox).Text
        .Email = DirectCast(fv_Usuario.FindControl("txt_Email"), TextBox).Text
      End With
      If boolInsercao Then
        BCUsuario.Cadastrar(usuario)
      Else
        BCUsuario.Atualizar(usuario)
      End If
      Session("objBEUsuario") = usuario

      usuario.Senha = DirectCast(fv_Usuario.FindControl("txt_Senha1"), TextBox).Text
      If usuario.Senha.Length > 0 Then BCUsuario.AtualizarSenha(usuario)

    Catch ex As Exception
      mostraMensagemDeErro(IIf(boolInsercao, MESSAGE_ERRO_NA_INSERCAO, MESSAGE_ERRO_NA_ALTERACAO))
      booSucesso = False
    End Try
    Return booSucesso
  End Function

  Protected Sub lbl_Franquia_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Session("FranquiaParaConsulta") = DirectCast(Session("objBEUsuario"), BEUsuario).Franquia
    Response.Redirect("Franquia.aspx")
  End Sub

  Protected Sub grvRecados_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs)
    Try
      Dim objGridView As GridView = sender
      BCRecado.Excluir(New BERecado(Integer.Parse(objGridView.DataKeys(e.RowIndex)("IdRecado"))))
      grvRecados_RowDeleted(sender, Nothing)
    Catch ex As Exception
      Throw ex
    End Try
  End Sub

  Protected Sub grvRecados_RowDeleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeletedEventArgs)
    If e IsNot Nothing Then e.ExceptionHandled = True
    mostraRecados()
  End Sub

  Protected Sub grvRecados_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs)
    DirectCast(sender, GridView).PageIndex = e.NewPageIndex
    mostraRecados()
  End Sub

  Protected Sub grvRecados_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
    If e.CommandName.ToUpper() = "RESPONDER" Then
      Session("UsuarioParaConsulta") = e.CommandArgument
      Response.Redirect("~/Perfil.aspx")
    End If
  End Sub

End Class
